﻿namespace Sustainalytics.Portfolios.Service.Controllers
{
    using System;
    using System.Configuration;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Web.Http;

    using Newtonsoft.Json;

    using Sustainalytics.OAuth.Services.Common;
    using Sustainalytics.Portfolios.BL;
    using Sustainalytics.Portfolios.Service.Models;
    using Sustainalytics.Utils;
    using System.Web.Http.Cors;

    // petre: [AutoInvalidateCacheOutput]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/v1/export")]
    [LogControllerFilter(true, true, false)]
    public class PortfolioExportController : ApiController
    {
        private readonly PortfolioExportManagement _portfolioExportManager;

        private readonly PortfolioUserClaimsProcessor _userClaimsProcessor;

        private readonly string _templateFileName = "Portfolio Securities Template" + ".xlsx";

        public PortfolioExportController(PortfolioExportManagement portfolioExportManager, PortfolioUserClaimsProcessor userClaimsProcessor)
        {
            _portfolioExportManager = portfolioExportManager;
            this._userClaimsProcessor = userClaimsProcessor;
        }

        [Route("")]
        public HttpResponseMessage Get()
        {
            var excelTemplateFile = _portfolioExportManager.GetTemplateForPortfolioSecurities(
                _templateFileName,
                ConfigurationManager.AppSettings["templateFolder"] + @"\" + _templateFileName);

            using (var fs = new FileStream(excelTemplateFile, FileMode.Open, FileAccess.Read))
            {
                var result = Request.CreateResponse(HttpStatusCode.OK);

                result.Content = new StreamContent(fs);
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                return result;
            }
        }

        [Route("")]
        public HttpResponseMessage Post([FromBody] string exportDetailsDto)
        {
            try
            {
                if (exportDetailsDto == null)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorStatusCode = 5012 });
                }

                var exp = JsonConvert.DeserializeObject<PortfolioExportDto>(exportDetailsDto);

                exp.Name = RemoveIllegalCharacters.Remove(exp.Name);

                var userClaims = _userClaimsProcessor.GetPortfolioClaims();

                var file = _portfolioExportManager.GeneratePortfolioFile(exp.Id, GetFilePath(), userClaims);

                var result = Request.CreateResponse(HttpStatusCode.OK);

                var strContent = new PushStreamContent(
                    (outStream, httpContent, contex) =>
                        {
                            outStream.WriteAsync(file, 0, file.Length);
                            outStream.Close();
                        });

                strContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                strContent.Headers.Add(
                    "Content-Disposition",
                    string.Format(
                        " attachement; filename={0}_{1}_Export_{2}",
                        exp.Name,
                        Guid.NewGuid(),
                                    DateTime.Now.ToString("ddMMyyyy")));
                result.Content = strContent;
                return result;
            }
            catch (NullReferenceException ex)
            {
                PortfolioManagementEventSource.Log.GetPortfolioError(string.Empty, ex);
                return Request.CreateResponse(HttpStatusCode.BadRequest, new { ErrorStatusCode = 5012 });
            }
        }

        private static string GetFilePath()
        {
            var filePath = ConfigurationManager.AppSettings["templateFolder"] + @"\Sample Portfolio Export report.xlsx";
            return filePath;
        }
    }
}